package com.tang.common.resources;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tang.module.system.entity.User;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * mybatis自动填充类
 * @author tang
 * @date 2022/3/24 17:40
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //创建时间
        this.strictInsertFill(metaObject, "createTime", Date::new, Date.class);
        //创建人
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //如果当前登录了用户
        if (authentication != null && ! (authentication instanceof  AnonymousAuthenticationToken)){
            //获取当前用户
            User principal = (User)authentication.getPrincipal();
            //设置创建用户
            this.strictInsertFill(metaObject, "createUser", principal::getId, Long.class);
            //创建部门
            this.strictInsertFill(metaObject, "createDept", () -> Long.parseLong(principal.getDeptId()), Long.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新时间
        this.strictUpdateFill(metaObject, "updateTime", Date::new, Date.class);
        //更新人
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //如果当前登录了用户
        if (authentication != null && ! (authentication instanceof  AnonymousAuthenticationToken)){
            //获取当前用户
            User principal = (User)authentication.getPrincipal();
            //设置更新用户
            this.strictUpdateFill(metaObject, "updateUser", principal::getId, Long.class);
        }


    }


}
